<script setup lang="ts" name="HospitalCourse">
import {computed, onBeforeUnmount, onDeactivated, onMounted, reactive, ref} from 'vue'
import {HeaderData, Operation as Opr} from '@/components/dTable/dTable'
import dTablePromote from '@/components/dTable/dTable.vue'
import operation from '@/components//dTable/components/operation.vue'
import dIcon from '@/components/dIcon.vue'
import {ColorRed, ColorTheme, IconConfig} from '@/api/config'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import {ElMessage, FormRules} from 'element-plus/es'
import useUser from '@/store/user'
import {getHospitalCourse, HospitalCourse, rejectHospitalCourse, saveHospitalCourse} from '@/api/medicalExaminerDesk/beginPhysicalExamination/hospitalCourse'
import dayjs, {Dayjs} from 'dayjs'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
import {fieldRequired} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

// 控制是否现在校验提示
const showErrorTips = ref<boolean>(true)

//表格头数据
const tableHeaderDatas = ref<Array<HeaderData>>([
  {prop: 'inDate', label: '入/出院日期', columnType: 'slot', align: 'left', width: '300'},
  {prop: 'reason', label: '原因', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'unitsName', label: '医疗机构名称', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'caseNo', label: '病案号', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'operation', label: '操作', columnType: 'slot', width: '83'}
])

const tableHeaderDatas2 = ref<Array<HeaderData>>([
  {prop: 'inDate', label: '建/撤床日期', columnType: 'slot', align: 'left', width: '300'},
  {prop: 'reason', label: '原因', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'unitsName', label: '医疗机构名称', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'caseNo', label: '病案号', columnType: 'slot', align: 'left', 'min-width': '100'},
  {prop: 'operation', label: '操作', columnType: 'slot', width: '83'}
])

// 禁止编辑的时候去掉操作列
props.disEdit && (tableHeaderDatas.value = tableHeaderDatas.value.slice(0, -1))

// 禁止编辑的时候去掉操作列
props.disEdit && (tableHeaderDatas2.value = tableHeaderDatas2.value.slice(0, -1))

// 操作按钮数据
const operationDataDelete: Array<Opr> = [
  {
    code: 'delete',
    label: '删除',
    iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}
  }
]

// 操作按钮数据
const operationDataAdd: Array<Opr> = [
  {
    code: 'add',
    label: '添加',
    iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}
  }
]

// 表格加载
const showLoading = ref(false)

//体检医生id
const dutyDoctorId = ref<string | undefined>()
// 体检医生姓名
const dutyDoctorName = ref<string | undefined>()

// 空数据表格
const emptyTableData: HospitalCourse = {
  inDate: [],
  reason: '',
  unitsName: '',
  caseNo: '',
  checkupRegisterId: props.checkupRegisterId,
  dutyDoctorId: '',
  dutyDoctorName: ''
}

const formData = reactive<{hospitalizationTable: Array<HospitalCourse>; familyBedHistoryTable: Array<HospitalCourse>}>({
  // 住院史列表
  hospitalizationTable: [{...emptyTableData, ...{operation: operationDataAdd}}],
  // 家庭病床史列表
  familyBedHistoryTable: [{...emptyTableData, ...{operation: operationDataAdd}}]
})

// 错提示图标
const errorIcon: IconConfig = {
  icon: 'CircleCloseFilled',
  type: 'el',
  size: 16,
  color: ColorRed
}

// 表单实例
const formRef = ref()

// 体检大类的体检医生姓名
const dutyDoctorName6 = computed(() => {
  return dutyDoctorName.value || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

// 体检状态
const checkupStatus6 = computed(() => {
  return formData.hospitalizationTable[0]?.checkupStatus
})

const rules = computed<FormRules>(() => {
  return {
    // 住院史的校验规则
    inDate: [{required: fieldRequired('inEndDate'), message: '请选择入/出院日期!', trigger: []}],
    reason: [
      {required: fieldRequired('reason'), message: '请输入原因!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    unitsName: [
      {required: fieldRequired('unitsName'), message: '请输入医疗机构名称!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    caseNo: [
      {required: fieldRequired('caseNo'), message: '请输入病案号!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    // 家庭病床史的校验规则
    jtInEndDate: [{required: fieldRequired('jtInEndDate'), message: '请选择建/撤床日期!', trigger: []}],
    jtReason: [
      {required: fieldRequired('jtReason'), message: '请输入原因!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    jtUnitsName: [
      {required: fieldRequired('jtUnitsName'), message: '请输入医疗机构名称!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    jtCaseNo: [
      {required: fieldRequired('jtCaseNo'), message: '请输入病案号!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ]
  }
})

/**
 * @description: 改变当前行日期触发校验
 * @param {*} index
 * @return {*}
 */
const onChangeDate1 = (index: number) => {
  formRef.value && formRef.value.validateField(`hospitalizationTable.${index}.inDate`)
}

/**
 * @description: 改变当前行日期触发校验
 * @param {*} index
 * @return {*}
 */
const onChangeDate2 = (index: number) => {
  formRef.value && formRef.value.validateField(`familyBedHistoryTable.${index}.inDate`)
}

/**
 * @description: 添加展示按钮
 * @param {*} dataList
 * @return {*}
 */
const showButton = (dataList: Array<HospitalCourse>) => {
  formRef.value && formRef.value.clearValidate() // 清空校验
  const returnList: Array<HospitalCourse> = []
  dataList.map((item, index) => {
    returnList.push({...item, operation: index === dataList.length - 1 ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })
  return returnList
}

/**
 * @description: 删除住院史
 * @param {*} index
 * @return {*}
 */
const onRemoveHospitalization = (index: number) => {
  formData.hospitalizationTable.splice(index, 1)
  formData.hospitalizationTable = showButton(formData.hospitalizationTable)
  if (formData.hospitalizationTable.length === 0) {
    formData.hospitalizationTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
  }
}

/**
 * @description: 添加住院史
 * @return {*}
 */
const onAddHospitalization = () => {
  formData.hospitalizationTable.push(emptyTableData)
  formData.hospitalizationTable = showButton(formData.hospitalizationTable)
}

/**
 * @description: 住院史列表操作栏点击
 * @param {*} code
 * @param {*} row
 * @return {*}
 */
const onHospitalizationTableOper = (code: string, row: HospitalCourse) => {
  if (code === 'delete') {
    onRemoveHospitalization(formData.hospitalizationTable.indexOf(row))
  } else if (code === 'add') {
    onAddHospitalization()
  }
}

/**
 * @description: 删除家庭病床史
 * @param {*} index
 * @return {*}
 */
const onRemoveFamilyBed = (index: number) => {
  formData.familyBedHistoryTable.splice(index, 1)
  formData.familyBedHistoryTable = showButton(formData.familyBedHistoryTable)
  if (formData.familyBedHistoryTable.length === 0) {
    formData.familyBedHistoryTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
  }
}

/**
 * @description:添加家庭病床史
 * @return {*}
 */
const onAddFamilyBed = () => {
  formData.familyBedHistoryTable.push(emptyTableData)
  formData.familyBedHistoryTable = showButton(formData.familyBedHistoryTable)
}

/**
 * @description: 家庭病床史列表操作栏点击
 * @param {*} code
 * @param {*} row
 * @return {*}
 */
const onFamilyBedTableOper = (code: string, row: HospitalCourse) => {
  if (code === 'delete') {
    onRemoveFamilyBed(formData.familyBedHistoryTable.indexOf(row))
  } else if (code === 'add') {
    onAddFamilyBed()
  }
}

/**
 * @description: 禁用日期
 * @param {*} current
 * @return {*}
 */
const disabledDate = (current: Dayjs) => {
  return current && current > dayjs().endOf('day')
}

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  showLoading.value = true
  // 住院史列表
  const params = {
    checkupRegisterId: props.checkupRegisterId,
    styleSign: 0 // 0住院史
  }
  getHospitalCourse(params)
    .then((res) => {
      const {data} = res.data || []
      formData.hospitalizationTable = data?.map((item) => {
        // 获取当前行的体检医生
        item.dutyDoctorId && (dutyDoctorId.value = item.dutyDoctorId)
        item.dutyDoctorName && (dutyDoctorName.value = item.dutyDoctorName)
        return {
          id: item.id,
          checkupStatus: item.checkupStatus,
          checkupRegisterId: item.checkupRegisterId,
          dutyDoctorId: item.dutyDoctorId,
          dutyDoctorName: item.dutyDoctorName,
          caseNo: item.caseNo || '',
          reason: item.reason || '',
          unitsName: item.unitsName || '',
          inDate: item.inStartDate && item.inEndDate ? [item.inStartDate, item.inEndDate] : [],
          styleSign: item.styleSign
        }
      })
      if (formData.hospitalizationTable?.length === 0) {
        formData.hospitalizationTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
      }
      formData.hospitalizationTable = showButton(formData.hospitalizationTable)
    })
    .finally(() => {
      showLoading.value = false
      showSaveLoading.value = false
    })
  // 家庭病床史列表
  const params2 = {
    checkupRegisterId: props.checkupRegisterId,
    styleSign: 1 // 1家庭病床史
  }
  getHospitalCourse(params2)
    .then((res) => {
      const {data} = res.data || []
      formData.familyBedHistoryTable = data?.map((item) => {
        // 获取当前行的体检医生
        item.dutyDoctorId && (dutyDoctorId.value = item.dutyDoctorId)
        item.dutyDoctorName && (dutyDoctorName.value = item.dutyDoctorName)
        return {
          id: item.id,
          checkupStatus: item.checkupStatus,
          checkupRegisterId: item.checkupRegisterId,
          dutyDoctorId: item.dutyDoctorId,
          dutyDoctorName: item.dutyDoctorName,
          caseNo: item.caseNo,
          reason: item.reason,
          unitsName: item.unitsName,
          inDate: item.inStartDate && item.inEndDate ? [item.inStartDate, item.inEndDate] : [],
          styleSign: item.styleSign
        }
      })
      if (formData.familyBedHistoryTable?.length === 0) {
        formData.familyBedHistoryTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
      }
      formData.familyBedHistoryTable = showButton(formData.familyBedHistoryTable)
    })
    .finally(() => {
      showLoading.value = false
      showSaveLoading.value = false
    })
}

/**
 * @description: 保存
 * @return {*}
 */
const onSave6 = () => {
  showErrorTips.value = true
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        // 公共参数
        const baseParams = {
          checkupStatus: 2, //2已检
          checkupRegisterId: props.checkupRegisterId,
          dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
          dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName
        }
        const params = formData.hospitalizationTable
          .map((item) => {
            return {
              ...baseParams,
              caseNo: item.caseNo,
              reason: item.reason,
              unitsName: item.unitsName,
              inStartDate: item.inDate?.[0],
              inEndDate: item.inDate?.[1],
              styleSign: 0,
              id: item.id
            }
          })
          .concat(
            formData.familyBedHistoryTable.map((item) => {
              return {
                ...baseParams,
                caseNo: item.caseNo,
                reason: item.reason,
                unitsName: item.unitsName,
                inStartDate: item.inDate?.[0],
                inEndDate: item.inDate?.[1],
                styleSign: 1,
                id: item.id
              }
            })
          )
        saveHospitalCourse(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            console.warn(err)
            showSaveLoading.value = false
          })
      } else {
        console.warn(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection6 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      // 公共参数
      const baseParams = {
        checkupStatus: 1, // 1拒检
        checkupRegisterId: props.checkupRegisterId,
        dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
        dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName
      }
      const params = formData.hospitalizationTable
        .map((item) => {
          return {
            ...baseParams,
            caseNo: null,
            reason: null,
            unitsName: null,
            inStartDate: null,
            inEndDate: null,
            styleSign: 0,
            id: item.id
          }
        })
        .concat(
          formData.familyBedHistoryTable.map((item) => {
            return {
              ...baseParams,
              caseNo: null,
              reason: null,
              unitsName: null,
              inStartDate: null,
              inEndDate: null,
              styleSign: 1,
              id: item.id
            }
          })
        )
      rejectHospitalCourse(params)
        .then(() => {
          ElMessage.success('拒检成功!')
          getInitData()
        })
        .catch((error) => {
          console.warn(error)
          showSaveLoading.value = false
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

onMounted(() => {
  getInitData()
})

onBeforeUnmount(() => {
  showErrorTips.value = false
})

onDeactivated(() => {
  showErrorTips.value = false
})
</script>

<template>
  <div class="d-check-up-desk-content">
    <h1>住院史</h1>
    <el-form ref="formRef" :rules="rules" :model="formData" :disabled="disEdit">
      <d-table-promote
        class=".d-common-flex-full hospital-course-table"
        style="height: 330px"
        :table-data="formData.hospitalizationTable"
        :table-header-data="tableHeaderDatas"
        :show-loading="showLoading"
      >
        <template #inDate="scope">
          <el-form-item :prop="`hospitalizationTable.${scope.index}.inDate`" :rules="rules.inDate" :inline-message="true" class="d-common-width-full">
            <a-config-provider :locale="zhCN">
              <A-range-picker
                v-model:value="scope.row.inDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabled="disEdit"
                :placeholder="['开始时间', '结束时间']"
                @change="onChangeDate1(scope.index)"
              />
            </a-config-provider>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #reason="scope">
          <el-form-item :prop="`hospitalizationTable.${scope.index}.reason`" :rules="rules.reason" :inline-message="true">
            <el-input v-model="scope.row.reason" placeholder="请输入原因" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #unitsName="scope">
          <el-form-item :prop="`hospitalizationTable.${scope.index}.unitsName`" :rules="rules.unitsName" :inline-message="true">
            <el-input v-model="scope.row.unitsName" placeholder="请输入医疗机构名称" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #caseNo="scope">
          <el-form-item :prop="`hospitalizationTable.${scope.index}.caseNo`" :rules="rules.caseNo" :inline-message="true">
            <el-input v-model="scope.row.caseNo" placeholder="请输入病案号" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="top"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #operation="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onHospitalizationTableOper" />
        </template>
      </d-table-promote>
      <h1>家庭病床史</h1>
      <d-table-promote
        class=".d-common-flex-full hospital-course-table"
        style="height: 330px"
        :table-data="formData.familyBedHistoryTable"
        :table-header-data="tableHeaderDatas2"
        :show-loading="showLoading"
      >
        <template #inDate="scope">
          <el-form-item :prop="`familyBedHistoryTable.${scope.index}.inDate`" :rules="rules.jtInEndDate" :inline-message="true" class="d-common-width-full">
            <a-config-provider :locale="zhCN">
              <A-range-picker
                v-model:value="scope.row.inDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabled="disEdit"
                :placeholder="['开始时间', '结束时间']"
                :locale="zhCN"
                @change="onChangeDate2(scope.index)"
              />
            </a-config-provider>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #reason="scope">
          <el-form-item :prop="`familyBedHistoryTable.${scope.index}.reason`" :rules="rules.jtReason" :inline-message="true">
            <el-input v-model="scope.row.reason" placeholder="请输入原因" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #unitsName="scope">
          <el-form-item :prop="`familyBedHistoryTable.${scope.index}.unitsName`" :rules="rules.jtUnitsName" :inline-message="true">
            <el-input v-model="scope.row.unitsName" placeholder="请输入医疗机构名称" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #caseNo="scope">
          <el-form-item :prop="`familyBedHistoryTable.${scope.index}.caseNo`" :rules="rules.jtCaseNo" :inline-message="true">
            <el-input v-model="scope.row.caseNo" placeholder="请输入病案号" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="top"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #operation="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onFamilyBedTableOper" />
        </template>
      </d-table-promote>
    </el-form>
  </div>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName6" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave6()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="(checkupStatus6 && checkupStatus6 === 1) || disEdit" plain @click="onRejectInspection6()">
      拒检
    </el-button>
  </div>
</template>

<style scoped lang="less">
h1 {
  font-size: 14px;
  font-weight: bold;
  color: var(--d-font-color-text);
  margin-bottom: 20px;
}
.hospital-course-table {
  margin-bottom: 50px;
}
</style>
